package com.ykdl.member.kid.adapters;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.ykdl.member.kid.R;
import com.ykdl.member.kid.adapters.base.BaseListAdapter;
import com.ykdl.member.kid.adapters.base.ViewHolder;
import com.ykdl.member.kid.beans.ChatBean;
import com.ykdl.member.kid.chat.ChatConfig;
import com.ykdl.member.kid.chat.ImageBrowserActivity;
import com.ykdl.member.kid.util.DateUtil;
import com.ykdl.member.kid.util.ImageLoadOptions;
import com.ykdl.member.kid.util.TimeUtil;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.text.SpannableString;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

public class MessageChatAdapter extends BaseListAdapter<ChatBean>{
	// 4种Item的类型
	// 文本
	private final int TYPE_RECEIVER_TXT = 0;
	private final int TYPE_SEND_TXT = 1;
	// 图片
	private final int TYPE_SEND_IMAGE = 2;
	private final int TYPE_RECEIVER_IMAGE = 3;
	private DisplayImageOptions options;
	private ImageLoadingListener animateFirstListener = new AnimateFirstDisplayListener();
	public MessageChatAdapter(Context context, ArrayList<ChatBean> list) {
		super(context, list);
		// TODO Auto-generated constructor stub
		options = new DisplayImageOptions.Builder()
		.showImageOnLoading(R.drawable.load_lost_bg)            //加载图片时的图片  
        .showImageForEmptyUri(R.drawable.load_lost_bg)         //没有图片资源时的默认图片  
        .showImageOnFail(R.drawable.load_lost_bg) 
		.showStubImage(R.drawable.load_lost_bg)
		.resetViewBeforeLoading(true)
		.cacheOnDisc(true)
		.cacheInMemory(true)
		.imageScaleType(ImageScaleType.EXACTLY)
		.bitmapConfig(Bitmap.Config.RGB_565)
		.considerExifParams(true)
		.displayer(new FadeInBitmapDisplayer(300))
		.build();
	}
	@Override
	public int getItemViewType(int position) {
		ChatBean msg = list.get(position);
		if(msg.getAttachment_type()==ChatConfig.TYPE_IMAGE){
			return msg.isFrom_self() ? TYPE_SEND_IMAGE: TYPE_RECEIVER_IMAGE;
		}else{
		    return msg.isFrom_self() ? TYPE_SEND_TXT: TYPE_RECEIVER_TXT;
		}
	}
	@Override
	public int getViewTypeCount() {
		return 8;
	}
	private View createViewByType(ChatBean message, int position) {
		int type = message.getAttachment_type();
	   if(type==ChatConfig.TYPE_IMAGE){//图片类型
			return getItemViewType(position) == TYPE_RECEIVER_IMAGE ? 
					mInflater.inflate(R.layout.item_chat_received_image, null) 
					:
					mInflater.inflate(R.layout.item_chat_sent_image, null);
		}else{//剩下默认的都是文本
			return getItemViewType(position) == TYPE_RECEIVER_TXT ? 
					mInflater.inflate(R.layout.item_chat_received_message, null) 
					:
					mInflater.inflate(R.layout.item_chat_sent_message, null);
		}
	}

	@Override
	public View bindView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		final ChatBean item = list.get(position);
		if (convertView == null) {
			convertView = createViewByType(item, position);
		}
		//文本类型
		ImageView iv_avatar = ViewHolder.get(convertView, R.id.iv_avatar);
		final ImageView iv_fail_resend = ViewHolder.get(convertView, R.id.iv_fail_resend);//失败重发
		final TextView tv_send_status = ViewHolder.get(convertView, R.id.tv_send_status);//发送状态
		TextView tv_time = ViewHolder.get(convertView, R.id.tv_time);
		TextView tv_message = ViewHolder.get(convertView, R.id.tv_message);
		//图片
		ImageView iv_picture = ViewHolder.get(convertView, R.id.iv_picture);
		final ProgressBar progress_load = ViewHolder.get(convertView, R.id.progress_load);//进度条
		
		//点击头像进入个人资料
		if (item.getFrom_actor()!=null) {
			if (item.getFrom_actor().getAvatar()!=null) {
				String avatar = item.getFrom_actor().getAvatar().getFile_url();
				ImageLoader.getInstance().displayImage(avatar, iv_avatar, ImageLoadOptions.getOptions(),animateFirstListener);
			}else {
				iv_avatar.setImageResource(R.drawable.defualt_icon);
			}	
		}
		
//		tv_time.setText(TimeUtil.getChatTime(Long.parseLong(item.getCreated_time())));
		tv_time.setText(DateUtil.gettopicDate(item.getCreated_time()));
		
		if(getItemViewType(position)==TYPE_SEND_TXT){//只有自己发送的消息才有重发机制
			//状态描述
			if(item.getStatus()==ChatConfig.STATUS_SEND_SUCCESS){//发送成功
				progress_load.setVisibility(View.INVISIBLE);
				iv_fail_resend.setVisibility(View.INVISIBLE);
				tv_send_status.setVisibility(View.VISIBLE);
//				tv_send_status.setText("已发送");
			}else if(item.getStatus()==ChatConfig.STATUS_SEND_START){//
				progress_load.setVisibility(View.VISIBLE);
				iv_fail_resend.setVisibility(View.INVISIBLE);
				tv_send_status.setVisibility(View.INVISIBLE);
			}
		}
		//根据类型显示内容
		final String text = item.getContent();
		switch (item.getAttachment_type()) {
		case ChatConfig.TYPE__TXT:
				tv_message.setText(text);
			break;

		case ChatConfig.TYPE_IMAGE://图片类
			final String url = item.getAttachments().get(0).getFile_url();
			try {
				if (url != null && !url.equals("")) {//发送成功之后存储的图片类型的content和接收到的是不一样的
					dealWithImage(position, progress_load, iv_fail_resend, tv_send_status, iv_picture, item);
				}
				iv_picture.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View arg0) {
						// TODO Auto-generated method stub
						Intent intent =new Intent(mContext,ImageBrowserActivity.class);
						ArrayList<String> photos = new ArrayList<String>();
						photos.add(item.getAttachments().get(0).getFile_url());
						intent.putStringArrayListExtra("photos", photos);
						intent.putExtra("position", 0);
						mContext.startActivity(intent);
					}
				});
				
			} catch (Exception e) {
			}
			break;
			
		
		default:
			break;
		}
		return convertView;
	}
	/** 处理图片
	  * @Description: TODO
	  * @param @param position
	  * @param @param progress_load
	  * @param @param iv_fail_resend
	  * @param @param tv_send_status
	  * @param @param iv_picture
	  * @param @param item 
	  * @return void
	  * @throws
	  */
	private void dealWithImage(int position,final ProgressBar progress_load,ImageView iv_fail_resend,TextView tv_send_status,ImageView iv_picture,ChatBean item){
		String text = item.getAttachments().get(0).getFile_url();
		if(getItemViewType(position)==TYPE_SEND_IMAGE){//发送的消息
			if(item.getStatus()==ChatConfig.STATUS_SEND_START){
				progress_load.setVisibility(View.VISIBLE);
				iv_fail_resend.setVisibility(View.INVISIBLE);
				tv_send_status.setVisibility(View.INVISIBLE);
			}else if(item.getStatus()==ChatConfig.STATUS_SEND_SUCCESS){
				progress_load.setVisibility(View.INVISIBLE);
				iv_fail_resend.setVisibility(View.INVISIBLE);
				tv_send_status.setVisibility(View.VISIBLE);
//				tv_send_status.setText("已发送");
			}else if(item.getStatus()==ChatConfig.STATUS_SEND_FAIL){
				progress_load.setVisibility(View.INVISIBLE);
				iv_fail_resend.setVisibility(View.VISIBLE);
				tv_send_status.setVisibility(View.INVISIBLE);
			}
//			如果是发送的图片的话，因为开始发送存储的地址是本地地址，发送成功之后存储的是本地地址+"&"+网络地址，因此需要判断下
			String showUrl = "";
			if(text.contains("http://")){
				showUrl =text;
			}else{
				showUrl = "file://"+text;
			}
			//为了方便每次都是取本地图片显示
			ImageLoader.getInstance().displayImage(showUrl, iv_picture,options);
		}else{
			ImageLoader.getInstance().displayImage(text, iv_picture,options,new ImageLoadingListener() {
				
				@Override
				public void onLoadingStarted(String imageUri, View view) {
					// TODO Auto-generated method stub
					progress_load.setVisibility(View.VISIBLE);
				}
				
				@Override
				public void onLoadingFailed(String imageUri, View view,
						FailReason failReason) {
					// TODO Auto-generated method stub
					progress_load.setVisibility(View.INVISIBLE);
				}
				
				@Override
				public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
					// TODO Auto-generated method stub
					progress_load.setVisibility(View.INVISIBLE);
				}
				
				@Override
				public void onLoadingCancelled(String imageUri, View view) {
					// TODO Auto-generated method stub
					progress_load.setVisibility(View.INVISIBLE);
				}
			});
		}
	}
	private static class AnimateFirstDisplayListener extends SimpleImageLoadingListener {

		static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());

		@Override
		public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
			if (loadedImage != null) {
				ImageView imageView = (ImageView) view;
				boolean firstDisplay = !displayedImages.contains(imageUri);
				if (firstDisplay) {
					FadeInBitmapDisplayer.animate(imageView, 500);
					displayedImages.add(imageUri);
				}
			}
		}
	}
}
